// pages/step/step.js

const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    userInfo:'',
    pops:false,
    popStatus:false,
    step:0,
    show:true,
    banner:'/banner6.gif',
    money:0,
    isshow:0,
    nav:[
      {
        id:1,
        title:'个人排行榜'
      },
      {
        id:2,
        title:'今日排行榜'
      }
    ],
    navIndex:0,
    status:true,
    saveStatus:false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  donate:function(){
    var that = this;

     if(this.data.step==0){
      wx.showToast({
        title: '您今天还没走动过哦',
        icon:'loading',
        duration:1500
      })
      return false;
     }
     if(this.data.step<1000){
      wx.showToast({
        title: '不满1000步无法捐步哦',
        icon:'loading',
        duration:1500
      })
      return false;
     }
    var resPrice = that.data.money;
    var userInfo =wx.getStorageSync("userInfo");
    var openid = wx.getStorageSync("openid");
    wx.request({
      url: app.globalData.baseUrl + '/api/index/Pay',
      data: {
        openid: openid,
        nickname: userInfo.nickName,
        name:userInfo.nickName,
        headimg:userInfo.avatarUrl,
        price: resPrice,
        donate_type:3,
        donate_type_id:0,
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值
      },
      method: "POST",
      success: function (res) {
        console.log(res.data.payMap);
        that.doWxPay(res.data.payMap);
      },
      fail: function (err) {
        wx.showToast({
          icon: "none",
          title: '服务器异常，清稍候再试'
        })
      },
    });


   
  },
  doWxPay(param) {
    var that =this;
    var openid = wx.getStorageSync("openid");
    var userInfo =wx.getStorageSync("userInfo");
    var step =that.data.step;
    //小程序发起微信支付
    wx.requestPayment({
      timeStamp: param.timeStamp,
      nonceStr: param.nonceStr,
      package: param.package,
      signType: 'MD5',
      paySign: param.paySign,
      success: function (event) {
        // success
        console.log(event);

        wx.request({
          url: app.globalData.baseUrl  + '/api/index/saveRun',
          data: {
            openid:openid,
            num:step,
            nickname:userInfo.nickName,
            headimg:userInfo.avatarUrl,
          },
          header: {
            "Content-Type": "application/json" // 默认值
          },
          method: 'POST',
          success(res) {
            var res = res.data;
            if(res.code==1){
              wx.showToast({
                title: '您今天已经捐过啦',
                icon:'loading',
                duration:1500
              })
            }else{
              wx.showToast({
                title: '捐步成功',
                icon:'success',
                duration:1500,
                popStatus:false
              })
              that.setData({
                status:false
               })
            }
           
          }
      })


        wx.showToast({
          title: '支付成功',
          icon: 'success',
          duration: 2000
        });

        var date = new Date();
        var time = date.getFullYear()+'-'+(date.getMonth()+1)+'-'+date.getDate();
        that.saveImg(userInfo.nickName,'运动捐步',time,that.data.money); 
        that.setData({
          popStatus:false
        })

      },

      fail: function (error) {
        console.log("支付失败")
        console.log(error)
      },
      complete: function () {
        console.log("pay complete");

      }
    });

  },
  showpop:function(){
      this.setData({
        popStatus:true
      })
  },
  closepop:function(){
    this.setData({
      popStatus:false
    })
},
  changeNav:function(e){
    if(e.currentTarget.dataset.index==0){
      this.setData({
        navIndex:e.currentTarget.dataset.index,
        show:true
      })
    }else{
      this.setData({
        navIndex:e.currentTarget.dataset.index,
        show:false
      })
    }
  },
  onLoad: function (options) {
    var userInfo = wx.getStorageSync("userInfo");
    if (userInfo != '') {
      this.setData({
        userInfo: userInfo
      })
    };
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

    var that = this;
    var openid = wx.getStorageSync("openid");
    var userInfo =wx.getStorageSync("userInfo");
    wx.request({
      url: app.globalData.baseUrl  + '/api/index/getRunRank',
      header: {
        "Content-Type": "application/json" 
      },
      method: 'POST',
      success(res) {
        console.log(res.data);
        that.setData({
          data: res.data.data.total,
          data2: res.data.data.today,
          total_run:res.data.data.total_run,
          total_money:res.data.data.total_money
        })
        var todaydata =res.data.data.today;
        for (let i = 0; i < todaydata.length; i++) {
          console.log(todaydata[i])
          if(openid==todaydata[i]['openid']){
            that.setData({
              popStatus:false,
              status:false
            })
      
          }
        }

      
      }
  })
  that.getRun();





  },

  getRun: function () {
    var that =this;
    wx.login({
      success: function (res) {
       let code = res.code
       wx.request({
        url: app.globalData.baseUrl  + '/api/index/jscode2session',
        data: {
          code: res.code,
        },
        header: {
          "Content-Type": "application/x-www-form-urlencoded" 
        },
        method: 'POST',
        success(res) {
          var res = res.data;
          console.log(res);
          if (res.status == 1) {
            wx.setStorageSync("session_key", res.data.session_key);

            wx.getWeRunData({//解密微信运动
              success(res) {
                console.log(res)
                var session_key = wx.getStorageSync("session_key");
                wx.request({
                  url: app.globalData.baseUrl  + '/api/index/decryptData',
                  data: {
                    session:session_key,
                    encryptedData:res.encryptedData,
                    iv:res.iv
                  },
                  header: {
                    "Content-Type": "application/json" // 默认值
                  },
                  method: 'POST',
                  success(res) {
                    var res = res.data;
                    var money = (res.data.stepInfoList[30].step/10000);
                    money = money.toFixed(2);
                    that.setData({
                      step: res.data.stepInfoList[30].step,
                      money:money
                    });
                      
                  }
              })
              },
              fail: function(res) {
                wx.showModal({
                title: '提示',
                content: '获取微信运动步数，需要开启计步权限',
                success: function(res) {
                if (res.confirm) {
                //跳转去设置
                  wx.openSetting({
                  success: function(res) {
                  that.onLoad()
                  }
                  })
                }else{
                  wx.reLaunch({
                    url: '/pages/main/main'
                  })
                }
                }
                })
              }
            





              









             })
          } 
        }
      })
      }
     })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var that = this;
    return {
      title: '和善龙江 运动捐步',
      path:'/pages/main/main',
       imageUrl: 'http://cdn2.kyhdmedia.com/xcx_ljcs/share.jpg'
    }
  },
  onShareTimeline: function () {
    var that = this;
    return {
      title: '和善龙江 运动捐步',
      path:'/pages/main/main',
       imageUrl: 'http://cdn2.kyhdmedia.com/xcx_ljcs/share.jpg'
    }
  },
  saveImg:function(name1,title1,time,money){
    wx.showLoading({
      title: '合成海报中',
    });
    var that  = this;
    that.setData({
      saveStatus:true
    });
    var userInfo = that.data.userInfo;
    var context = wx.createCanvasContext('mycanvas',that);
    context.setFillStyle("#ffe200")
    context.fillRect(0, 0, 640, 945)
    var path1 = userInfo.avatarUrl;
    var path2 = "https://donate.kyhdmedia.com/static/uploads/app/post1.png";
    var path3 = "https://donate.kyhdmedia.com/static/uploads/app/er.png";
    let promise1 = new Promise(function(resolve, reject) {
      wx.getImageInfo({
        src: path1,
        success: function(res) {
          resolve(res.path);
        }
      })
    });
    let promise2 = new Promise(function(resolve, reject) {
      wx.getImageInfo({
        src: path2,
        success: function(res) {
          resolve(res.path);
        }
      })
    });
    let promise3 = new Promise(function(resolve, reject) {
      wx.getImageInfo({
        src: path3,
        success: function(res) {
          resolve(res.path);
        }
      })
    });
    
    Promise.all([promise1,promise2,promise3]).then(res=>{
      context.drawImage(res[0], 265,304, 114, 114);
      context.drawImage(res[1], 0, 0, 640, 945);
      context.drawImage(res[2], 50, 722, 136, 134);
      var name = '亲爱的'+name1;
      var l = 0;
      var title = "";
      for(var i=0; i<name.length; i++)
      {
        var reg=/^[\u4E00-\u9FA5]+$/;
        var reg1 = /[\u3002|\uff1f|\uff01|\uff0c|\u3001|\uff1b|\uff1a|\u201c|\u201d|\u2018|\u2019|\uff08|\uff09|\u300a|\u300b|\u3008|\u3009|\u3010|\u3011|\u300e|\u300f|\u300c|\u300d|\ufe43|\ufe44|\u3014|\u3015|\u2026|\u2014|\uff5e|\ufe4f|\uffe5]/;
        if(reg.test(name[i])||reg1.test(name[i]))
        {
          l+=2;
        }else{
          l+=1;
        }
        if(l>40)
        {
          title = name.substring(0,i-1)+'...';
          break;
        }
      }
      if(l<=40){
        title = name;
      }
      context.setFillStyle('#4d2600');
      context.setFontSize(24);
      context.fillText(title,70, 480);
      
      // context.
      context.setTextAlign('left');  
      var l = 0;
      var j = 0;
      var k = 0;
      var lg = [36,42,42,42,42];
      var txt = [];
      var yes = false;
      var totalrun =money*10000;
      var word = '感谢您于'+time+'向佛山市顺德区龙江慈善会的运动捐步'+totalrun+'步，捐款￥'+money+'元。我们将遵照您的意愿，全部用于公益慈善事业。对于您的善行义举，致以诚挚的敬意。';
      for(var i=0; i<word.length; i++)
      {
        var reg=/^[\u4E00-\u9FA5]+$/;
        var reg1 = /[\u3002|\uff1f|\uff01|\uff0c|\u3001|\uff1b|\uff1a|\u201c|\u201d|\u2018|\u2019|\uff08|\uff09|\u300a|\u300b|\u3008|\u3009|\u3010|\u3011|\u300e|\u300f|\u300c|\u300d|\ufe43|\ufe44|\u3014|\u3015|\u2026|\u2014|\uff5e|\ufe4f|\uffe5]/;
        var add = 0;
        if(reg.test(word[i])||reg1.test(word[i]))
        {
          add=2;
        }else{
          add=1;
        }
        l+=add;
        if(l==lg[k])
        {
          txt.push(word.substring(j,i+1));
          console.log(i);
          j = i+1;
          l = 0;
          k++;
          yes = true;
        }else if(l>lg[k])
        {
          txt.push(word.substring(j,i));
          j = i;
          l = add;	
          yes = true;
          k++;
        }else if(i==word.length-1)
        {
          if(l<lg[k])
          {
            k++;
            txt.push(word.substring(j,word.length));
          }
        }
      }
      console.log(txt);  
      var xx  = [120,70,70,70,70];
      var yy  = [530,575,620,665,710];
      for(var i=0; i<txt.length; i++)
      {
        context.fillText(txt[i],xx[i], yy[i],508);
      }
      context.setTextAlign('left');  
      var company = '佛山市顺德区龙江慈善会';
      context.fillText(company,574-context.measureText(company).width,774);
      context.fillText(time,574-context.measureText(time).width,816);
      context.draw();
      setTimeout(function () {
        wx.canvasToTempFilePath({
          canvasId: 'mycanvas',
          fileType: 'png',
          destWidth: 640,
          destHeight: 945,
          success: function (res) {
            var tempFilePath = res.tempFilePath;
            console.log(tempFilePath);
            wx.hideLoading();
            that.setData({
              imagePath: tempFilePath,
              pops:true,
              saveStatus:false
            });
          },
          fail: function (res) {
            console.log(res);
          }
        })  
      }, 2000);
    })
  },
  confrimPop:function(){
    this.setData({
      pops:false
    });
  },
  downImg(e){
    console.log(1);
    var self = this;
    wx.getSetting({
      success(res) {
        if (!res.authSetting['scope.writePhotosAlbum']) {
          wx.authorize({
            scope:'scope.writePhotosAlbum',
            success() {
              wx.saveImageToPhotosAlbum({
                filePath: self.data.imagePath,
                success: function (data) {
                  wx.showToast({
                    title: '保存成功',
                    icon: 'success',
                    duration: 2000
                  })
                }
              })
            },
            fail() {
              wx.showModal({
                title: "qing信息失败",
                content: "请允许授权以便为您提供给服务",
                success: function(e) {
                    e.confirm && this.getUserProfile();
                  }
              });
            },
          })
        }else{
          wx.saveImageToPhotosAlbum({
                filePath: self.data.imagePath,
                success: function (data) {
                  wx.showToast({
                    title: '保存成功',
                    icon: 'success',
                    duration: 2000
                  })
                }
              })
        }
      }
    })
  }
})